import os
import sys
#
def check_param()->int:
    if len(sys.argv)<2:
        print(f"usage {sys.argv[0]} <code/data baseaddr>")
        exit(-1)
    try:
        baseaddr = int(sys.argv[1])
        return baseaddr
    except Exception :
        baseaddr = int(sys.argv[1],16)
        return baseaddr

def main():
    """
    [Global Descriptor Table](gdtinfo.md)
    """
    baseaddr = check_param()
    limit_data = 0xFFFFF
    limit_code = 0x0FFFF
    access_code =       {"P":1,
                        "DPL":0,
                        "S":1,
                        "E":1,
                        "DC":0,
                        "RW":1,
                        "A":0}
    access_bites_code =     access_code["A"]|access_code["RW"]<<1| \
                            access_code["DC"]<<2|access_code["E"]<<3| \
                            access_code["S"]<<4|access_code["DPL"]<<5| \
                            access_code["P"]<<7
    access_code =       {"P":1,
                        "DPL":0,
                        "S":1,
                        "E":0,
                        "DC":0,
                        "RW":1,
                        "A":0}
    access_bites_data =     access_code["A"]|access_code["RW"]<<1| \
                            access_code["DC"]<<2|access_code["E"]<<3| \
                            access_code["S"]<<4|access_code["DPL"]<<5| \
                            access_code["P"]<<7
    
    flags = 0b1100 
    with open("gen_unrealmodgdt.asm","w") as f:
        f.write(
                f"""
gdtinfo:
   dw gdt_end - gdt - 1   ;last byte in table
   dd gdt

align 16
gdt:        
    dd 0,0  
codedesc:
db  {hex(limit_code & 0xff):>10}
db  {hex(limit_code>>8 & 0xff):>10}
db  {hex(baseaddr & 0xff):>10}
db  {hex(baseaddr>>8 & 0xff):>10}
db  {hex(baseaddr>>16&0xff):>10}
db  {hex(access_bites_code):>10}
db  {hex((limit_code>>16 &0xf)):>10}
db  {hex((baseaddr & 0xff000000)>>24):>10}

flatdesc: 
db  {hex(limit_data & 0xff):>10}
db  {hex(limit_data>>8 & 0xff):>10}
db  {hex(baseaddr & 0xff):>10}
db  {hex(baseaddr>>8 & 0xff):>10}
db  {hex(baseaddr>>16&0xff):>10}
db  {hex(access_bites_data):>10}
db  {hex(flags<<4|(limit_data>>16 &0xf)):>10}
db  {hex((baseaddr & 0xff000000)>>24):>10}
gdt_end:

                """)
        
if __name__ == "__main__":
    main()